import 'package:aqua_plunge/constants/colors.dart';
import 'package:aqua_plunge/dao/purchase_dao.dart';
import 'package:aqua_plunge/http/app_manager.dart';
import 'package:aqua_plunge/model/purchase.dart';
import 'package:aqua_plunge/payment/in_app_purchase_page.dart';
import 'package:aqua_plunge/payment/in_app_purchase_service.dart';
import 'package:aqua_plunge/payment/pay_page.dart';
import 'package:aqua_plunge/widget/app_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_util_code/toast_utils.dart';
import 'package:get/get.dart';

import '../constants/constants.dart';
import '../controller/UserController.dart';
import '../cover/LogPvManager.dart';
import '../model/payment.dart';

class ShopPage extends StatefulWidget {
  const ShopPage({super.key});

  @override
  State<ShopPage> createState() => _ShopPageState();
}

class _ShopPageState extends State<ShopPage> {
  List<Purchase> datalist = [];
  final UserController _userController = Get.find<UserController>();

  final InAppPurchaseService _inAppPurchaseService = InAppPurchaseService();

  get _contentview => Obx(() => Column(
    children: [
      Center(
          child: Text(
            _userController.userInformation.availableCoins.toString(),
            style: const TextStyle(fontSize: 36, color: Colors.white),
          )),
      const SizedBox(
        height: 8,
      ),
      const Center(
        child: Text(
          'My Coins',
          style: TextStyle(color: AppColors.describeColor, fontSize: 18),
        ),
      ),
      _gridview
    ],
  ));

  get _gridview => Expanded(
      child: MediaQuery.removePadding(
          context: context,
          child: Padding(
              padding: const EdgeInsets.only(left: 0, right: 0),
              child: MasonryGridView.count(
                  crossAxisCount: 2,
                  crossAxisSpacing: 0,
                  mainAxisSpacing: 11,
                  itemCount: datalist.length,
                  itemBuilder: (BuildContext context, int index) =>
                      _buildItem(datalist[index])))));

  @override
  void initState() {
    super.initState();
    _loadPurchaseList();
    LogPvManager.stat(page: Constants.pagePurchase);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar('Coin Shop'),
      body: Container(
        decoration: const BoxDecoration(
            image: DecorationImage(
                image: AssetImage('images/img_primary_bg.png'),
                fit: BoxFit.fill)),
        child: Container(
          margin: const EdgeInsets.fromLTRB(24, 20, 24, 20),
          padding: const EdgeInsets.fromLTRB(12, 40, 2, 36),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              color: AppColors.boxbgColor),
          child: _contentview,
        ),
      ),
    );
  }

  void initiatePurchase(Payment payment) async {
    // 显示 loading 弹窗
    showDialog(
      context: context,
      barrierDismissible: false, // 禁止用户点击弹窗外部取消
      builder: (BuildContext context) {
        return const Center(child: CircularProgressIndicator());
      },
    );
    await _inAppPurchaseService.buyProduct(payment, () {
      // 处理购买失败
      // Navigator.of(context).pop(); // 关闭 loading 弹窗
      // 在这里可以显示错误提示
      ToastUtils.showCenter("Purchase failed or product not available");
    });

    // 关闭 loading 弹窗
    Get.back();
  }


  _buildItem(Purchase item) {
    return Stack(
      children: [
        InkWell(
          onTap: () {
            PurchaseDao.createRecharge(int.parse(item.code ?? '0'))
                .then((payment) {
              // Get.to(()=>PurchasePage(payment: payment));
              initiatePurchase(payment);
              LogPvManager.stat(page: Constants.pageCreateOrder);
            });
          },
          child: Container(
            margin: const EdgeInsets.only(top: 5, right: 8),
            padding: const EdgeInsets.fromLTRB(20, 28, 0, 28),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(12)),
            child: Column(
              children: [
                Row(
                  children: [
                    Text(
                      item.exchangeCoin.toString(),
                      style: const TextStyle(
                          fontSize: 20,
                          color: AppColors.coinColor,
                          fontWeight: FontWeight.w800),
                    ),
                    const SizedBox(
                      width: 4,
                    ),
                    Visibility(visible: item.discount != null && item.discount! >0,child: Image.asset(
                      'images/icon_red_arrow_down.png',
                      width: 16,
                      height: 16,
                    ),),
                    Text(
                      (item.discount !=null && item.discount! > 0)
                          ? '${(item.discount! * 100).toInt()}%'
                          : '',
                      style: const TextStyle(
                          fontSize: 12, color: AppColors.discountColor),
                    )
                  ],
                ),
                const SizedBox(height: 20),
                Row(
                  children: [
                    Text(
                      '\$${item.price}',
                      style: const TextStyle(fontSize: 18, color: Colors.black),
                    ),
                    const SizedBox(
                      width: 6,
                    ),
                    Text(
                      '\$${item.originalPrice}',
                      style: const TextStyle(
                          fontSize: 14,
                          color: AppColors.originPriceColor,
                          decoration: TextDecoration.lineThrough,
                          decorationColor: AppColors.originPriceColor),
                    )
                  ],
                )
              ],
            ),
          ),
        ),
        Positioned(
          right: 0,
          top: 0,
          child: item.tags == ""
              ? const SizedBox()
              : Image.asset(
                  item.tags! == 'Hot'
                      ? 'images/icon_hot.png'
                      : item.tags! == 'Big Deal'
                          ? 'images/icon_big_deal.png'
                          : 'images/icon_great_sale.png',
                  width: 75,
                  height: 30),
        )
      ],
    );
  }

  void _loadPurchaseList() async {
    datalist = (await PurchaseDao.getGoodslist())!;
    setState(() {});
  }
}
